# views.py
from flask_restx import Namespace, Resource, reqparse
from .modles import query_futures_account, \
    query_single_futures_contract, query_futures_orders, query_user_positions, \
    query_futures_tickers
from app import cache,socketio
import json



gateio_ns = Namespace('gateio', description='Gate.io 查询相关接口')

parser = reqparse.RequestParser()

# 已废弃
@gateio_ns.route('/get_one_futures_contract')

class FuturesContract(Resource):
    # 设置请求参数
    parser.add_argument('contract', required=True, help='Gate.io contract')
    parser.add_argument('settle', required=True, help='Gate.io settle')
    parser.add_argument('gate_key', required=True, help='Gate.io API key')
    parser.add_argument('gate_secret', required=True, help='Gate.io API secret')

    @gateio_ns.expect(parser)
    def get(self):
        """
        返回单个合约的详细信息
        """
        try:
            args = parser.parse_args()
            gate_key = args['gate_key']
            gate_secret = args['gate_secret']
            settle = args['settle']
            contract = args['contract']

            # 查询单个合约信息
            response = query_single_futures_contract(gate_key, gate_secret, settle, contract)
            return response, response.get("code", 200)
        except Exception as e:
            return {"message": f"服务器内部错误: {str(e)}", "code": 500}, 500


@gateio_ns.route('/futures_orders')
class FuturesOrders(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('gate_key', required=True, help='Gate.io API key')
    parser.add_argument('gate_secret', required=True, help='Gate.io API secret')
    parser.add_argument('settle', default='usdt', help='结算货币')
    parser.add_argument('status', default='open', help='订单状态')
    parser.add_argument('contract', required=False, help='合约类型')
    parser.add_argument('limit', type=int, default=100, help='最大记录数')
    parser.add_argument('offset', type=int, default=0, help='列表偏移量')
    parser.add_argument('last_id', help='上一次查询的最后一条记录ID')

    @gateio_ns.expect(parser)
    def get(self):
        """ 根据指定条件返回期货订单列表 """
        args = self.parser.parse_args()
        response = query_futures_orders(
            gate_key=args['gate_key'], gate_secret=args['gate_secret'],
            settle=args['settle'], status=args['status'], contract=args['contract'],
            limit=args['limit'], offset=args['offset'], last_id=args['last_id']
        )
        return response, response.get("code", 200)


@gateio_ns.route('/user_positions')
class UserPositions(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('gate_key', required=True, help='Gate.io API key')
    parser.add_argument('gate_secret', required=True, help='Gate.io API secret')
    parser.add_argument('settle', default='usdt', help='结算货币')
    parser.add_argument('holding', type=bool, default=True, help='是否只返回实际持仓')
    parser.add_argument('limit', type=int, default=100, help='返回记录的最大数量')
    parser.add_argument('offset', type=int, default=0, help='列表偏移量')

    @gateio_ns.expect(parser)
    def get(self):
        """
        查询用户的持仓信息
        """
        args = self.parser.parse_args()
        response = query_user_positions(
            gate_key=args['gate_key'],
            gate_secret=args['gate_secret'],
            settle=args['settle'],
            holding=args['holding'],
            limit=args['limit'],
            offset=args['offset']
        )
        return response, response.get("code", 200)


@gateio_ns.route('/futures_tickers')
class FuturesTickers(Resource):
    parser.add_argument('settle', required=True, help='结算货币')
    parser.add_argument('contract', help='合约标识，可选')
    parser.add_argument('gate_key', required=True, help='Gate.io API key')
    parser.add_argument('gate_secret', required=True, help='Gate.io API secret')

    @gateio_ns.expect(parser)
    def get(self):
        """
        返回指定合约的行情信息
        """
        args = parser.parse_args()
        cache_key = f"tickers_{args['settle']}_{args.get('contract')}"

        # 检查缓存中是否有数据
        cached_response = cache.get(cache_key)
        if cached_response:
            return json.loads(cached_response), 200

        # 从API获取最新数据
        response = query_futures_tickers(args['gate_key'], args['gate_secret'], args['settle'], args.get('contract'))

        # 缓存500毫秒 (即0.5秒)
        if response.get("code") == 200:
            cache.set(cache_key, json.dumps(response), timeout=1)  # 使用1秒的缓存时间代替0.5秒

        return response, response.get("code", 200)


@gateio_ns.route('/futures_contract_details')
class FuturesContractDetails(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('gate_key', required=True, help='Gate.io API key')
    parser.add_argument('gate_secret', required=True, help='Gate.io API secret')
    parser.add_argument('settle', required=True, help='结算货币')
    parser.add_argument('contract', required=True, help='合约标识，例如 BTC_USDT')

    @gateio_ns.expect(parser)
    def get(self):
        """
        返回单个合约的详细信息
        """
        args = parser.parse_args()
        response = query_single_futures_contract(args['gate_key'], args['gate_secret'], args['settle'],
                                                 args['contract'])
        return response, response.get("code", 200)


@gateio_ns.route('/futures_account')
class FuturesContractDetails(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('gate_key', required=True, help='Gate.io API key')
    parser.add_argument('gate_secret', required=True, help='Gate.io API secret')
    parser.add_argument('settle', required=True, help='结算货币')
    parser.add_argument('contract', required=False, help='合约')

    @gateio_ns.expect(parser)
    def get(self):
        """
        返回单个合约的详细信息
        """
        args = parser.parse_args()
        response = query_futures_account(args['gate_key'], args['gate_secret'], args['settle'], args['contract'])
        return response, response.get("code", 200)


@socketio.on('request_tickers')
def handle_request_tickers(data):
    try:
        gate_key = data['gate_key']
        gate_secret = data['gate_secret']
        settle = data['settle']
        contract = data.get('contract', 'BTC_USDT')  # 合约可以是可选的

        # 从模型调用查询函数
        tickers = query_futures_tickers(gate_key, gate_secret, settle, contract)
        socketio.emit('update_tickers', tickers)
    except Exception as e:
        socketio.emit('error', {'message': str(e)})